﻿using MuddyBoots.GreenlightQC.DataService.Enumeration;
using MuddyBoots.GreenlightQC.DataService.Model;
using MuddyBoots.GreenlightQC.Mobile.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MuddyBoots.GreenlightQC.DataService
{
    public class GreenlightQCMobile : IGreenlightQCMobile
    {
        public Model.Menu GetMenu(IDatabaseEntities database, int applicationIdentifier)
        {
            Model.Menu result = new Model.Menu();
            var entities = database.GetMenu(applicationIdentifier);

            var assessmentMenu = entities.FirstOrDefault(x => x.ParentID == null && x.Description.Equals("Assessments", StringComparison.InvariantCultureIgnoreCase));
            int assessmentMenuId = assessmentMenu.MenuID;

            var correctiveActonsMenu = entities.FirstOrDefault(x => x.ParentID == null && x.Description.Equals("Corrective Actions", StringComparison.InvariantCultureIgnoreCase));
            int correctiveActionsMenuId = correctiveActonsMenu.MenuID;

            var tasksMenu = entities.FirstOrDefault(x => x.ParentID == null && x.Description.Equals("Tasks", StringComparison.InvariantCultureIgnoreCase));
            int tasksMenuId = tasksMenu.MenuID;

            var reportsMenu = entities.FirstOrDefault(x => x.ParentID == null && x.Description.Equals("Reports", StringComparison.InvariantCultureIgnoreCase));
            int reportsMenuId = reportsMenu.MenuID;

            var assessments = new List<Model.MenuItem>(entities.Count(e => e.ParentID == assessmentMenuId));
            var correctiveActions = new List<Model.MenuItem>(entities.Count(e => e.ParentID == correctiveActionsMenuId));
            var tasks = new List<Model.MenuItem>(entities.Count(e => e.ParentID == tasksMenuId));
            var reports = new List<Model.MenuItem>(entities.Count(e => e.ParentID == reportsMenuId));

            foreach (var entity in entities.Where(x => x.ParentID != null))
            {
                if (entity.ParentID == assessmentMenuId)
                {
                    this.AddMenuItemToMenu(assessments, entity);
                }

                if (entity.ParentID == correctiveActionsMenuId)
                {
                    this.AddMenuItemToMenu(correctiveActions, entity);
                }

                if (entity.ParentID == tasksMenuId)
                {
                    this.AddMenuItemToMenu(tasks, entity);
                }

                if (entity.ParentID == reportsMenuId)
                {
                    this.AddMenuItemToMenu(reports, entity);
                }
            }

            result.Assessments = assessments;
            result.CorrectiveActions = correctiveActions;
            result.Tasks = tasks;
            result.Reports = reports;
            return result;
        }

        public Model.AssessmentType GetAssessmentType(IDatabaseEntities database, int assessmentType)
        {
            throw new NotImplementedException();
        }

        public void SaveAssessment(IDatabaseEntities database, IReadOnlyCollection<Model.Question> assessment)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Logs the in.
        /// </summary>
        /// <param name="database">The database.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public User LogIn(IDatabaseEntities database, string username, string password)
        {
            var procedureResults = database.ValidateCredentials(username, password, string.Empty);

            if (procedureResults.Count() < 1)
            {
                throw new UnauthorizedAccessException();
            }

            var entity = procedureResults.FirstOrDefault();

            User user = new User(entity.UserID, entity.FullName, entity.UserLevel, entity.UserName, entity.CountryLocaleID, entity.StringCode);

            int failedLogins = database.GetFailedLoginCount(entity.UserID);
            user.AccountStatus = failedLogins > 2 ? UserAccountStatus.Locked : UserAccountStatus.Valid;

            return user;
        }

        /// <summary>
        /// Gets the target identifier.
        /// </summary>
        /// <param name="menu">The menu.</param>
        /// <param name="subMenu">The sub menu.</param>
        /// <returns>The only useful bit of data in the databse field</returns>
        private int GetTargetIdentifier(QRY_Menu_Result menu, SubMenu subMenu)
        {
            switch (subMenu)
            {
                case SubMenu.Assessments:
                    string wtf = menu.MenuAction;
                    var parts = wtf.Split(';');
                    string interestingPart = parts[2];
                    string wrongFlamingType = interestingPart.Replace("AssessmentTypeID=", string.Empty);
                    int result = 0;
                    int.TryParse(wrongFlamingType, out result);
                    return result;
                case SubMenu.CorrectiveActions:
                    // Fucking Shite
                default:
                    return -1;
            }
        }

        private void AddMenuItemToMenu(List<Model.MenuItem> assessments, QRY_Menu_Result entity)
        {
            assessments.Add(new Model.MenuItem
            {
                Icon = entity.IconName,
                Index = entity.MenuIndex.GetValueOrDefault(0),
                TargetIdentifier = this.GetTargetIdentifier(entity, SubMenu.Assessments),
                Text = entity.Description
            });
        }
    }
}
